import React, { Component } from 'react'
import { View, Image, Text, Button } from '@tarojs/components'
import Taro from '@tarojs/taro';
import './wxLogin.less'
import { APIBASEURL, IMGURL } from "../constants/global";


class WXLogin extends Component {

  constructor(props) {
    super(props)
    this.state = {
      openid: ''
    }
  }

  //获取用户的openID，在数据库中查找是否存在该用户
  getuseropenid() {
    Taro.getStorage({
      key: 'openid',
      success: result => {
        console.log("获取的数据："+result.data)
        Taro.request({
          url: `${APIBASEURL}login/user?wxOpenid=`+result.data,
          // data: {
          //   wxOpenid: result.data.openid
          // },
          method: 'GET',
          header: {
            'content-type': 'application/json'
          },
          success: (res) => {
            if (res.data.code === -1) {//新用户
              Taro.navigateTo({ url: '/pages/myRecord/personData' })
            } else  if (res.data.code === 200) {//老用户
              Taro.setStorage({
                key: '__userInfo__',
                data: res.data.data
              })
              console.log("API返回：",res.data.data)
              console.log("API返回：",res.data.data.username)
              Taro.reLaunch({ url: '/pages/index/index' })
            }else if (res.data.code === -2) {   //表示用户没有给openid
              Taro.reLaunch({ url: '/pages/index/index' })
            }
          },
          fail: (err) => {//失联之类
            console.error('从数据库获取不到openID')
          }
        });
      }
    })
  }

  userLoin() {
    Taro.login({
      success: res => {
        // 获取到用户的 code 之后：res.code
        var code = res.code
        console.log("#用户code：" + code);
        // code = "033UGb2w3bNfVW2CSb2w3twBxP1UGb2D";
        // Taro.request({
        //   url: `${APIBASEURL}/login/wxlogin?code=${code}`,
        //   data: {
        //   },
        //   header: {
        //     'content-type': 'application/json'
        //   },
        //   success: (res) => {
        //     console.log('>>>>微信的提供的接口直接获取的信息：')

        //     const sessionKeyAndOpenid = JSON.parse(`${res.data.data}`)
        //     console.log("#接口信息：" + sessionKeyAndOpenid)
        //     Taro.setStorage({
        //       key: 'openid',
        //       data: sessionKeyAndOpenid
        //     })
        //     console.log('完成登录! openid = %s', sessionKeyAndOpenid.openid)
        //     //获取用户的openID，在数据库中查找是否存在该用户
        //     this.getuseropenid()
        //   }
        // })
        ///开始假设登录成功--------------------------
        console.log("开始假设登录成功")
        Taro.setStorage({
          key: 'openid',
          data: "hkjdsfhasdfhjojik2jo32fcsadgjhgjhewK",
          success:(res =>
            {
              this.getuseropenid()
            }
           )
        })
        //console.log('完成登录! openid = %s', sessionKeyAndOpenid.openid)
        //获取用户的openID，在数据库中查找是否存在该用户
    

        ////结束登录成功-----------------------------



      }
    })
  }

  bindGetUserInfo(e) {
    if (e.detail.userInfo) {
      //用户按了允许授权按钮

      new Promise((resolve, reject) => {
        //用户登录获取openid
        this.userLoin()
        resolve()
      }).then(() => {
      })

      Taro.setStorage({
        key: '__userInfo__',
        data: e.detail.userInfo
      })
      console.log("数据：" + e.detail.userInfo);
    } else {
      //用户按了拒绝按钮
      Taro.showModal({
        title: '警告',
        content: '您点击了拒绝授权，将无法进入小程序，请授权之后再进入!!!',
        showCancel: false,
        confirmText: '返回授权',
        success: function (res) {
          if (res.confirm) {
            //console.log('用户点击了“返回授权”');
          }
        }
      });
    }
  }

  render() {
    return (
      <View>
        <view>
          <view className='header'>
            <Image src={`${IMGURL}login/appwx_logo.png`} ></Image>
          </view>
          <view className='wx-content'>
            <view>申请获取以下权限</view>
            <Text>获得你的公开信息(昵称，头像等)</Text>
          </view>

          <Button className='bottom' type='primary' openType='getUserInfo'
            onGetUserInfo={this.bindGetUserInfo.bind(this)}>
            授权登录</Button>
        </view>
      </View>
    );
  }
}

export default WXLogin
